<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Login extends Controller
{
     public function action_login()
    {
        if ($_POST)
        {
            if (empty($_POST['username']) || empty($_POST['password']))
            {
                Message::set('用户名或密码不能为空', 'error');
            }
            $data = array();
            $data['username'] = Arr::get($_POST, 'username', '');
            $data['password'] = Arr::get($_POST, 'password', '');
            $user_id = User::instance()->login($data);
            if ($user_id)
            {
                Message::set('登录成功！');
                $session = Session::instance();
                $session->set('user_id', $user_id);
                $session->set('manager_active_time', time()); //用户最后操作时间
                if (!$redirect = Arr::get($_REQUEST, 'redirect', 0) OR !Toolkit::is_our_url($redirect))
                {
                    if (!$redirect = Arr::get($_REQUEST, 'referer', 0) OR !Toolkit::is_our_url($redirect))
                    {
                      $redirect = Url::base().'admin/user/list';
                    }
                }
                Request::current()->redirect($redirect);
            }
            else
            {
                message::set('登录失败,请重新登录', 'error');
            }
        }

        $content['referer'] = (isset($_SERVER['HTTP_REFERER']) AND toolkit::is_our_url($_SERVER['HTTP_REFERER'])) ?
                $_SERVER['HTTP_REFERER'] : 0;
        $content['redirect'] = Arr::get($_GET, 'redirect', 0);
        $view = View::factory('admin/login',$content);
        $this->response->body($view);
    }
}